package cn.edu.jssvc.rollcall;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;

import cn.edu.jssvc.rollcall.util.HttpUtil;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;



public class MainActivity extends BaseActivity {

    private static final int TAKE_PHOTO = 1;
    private static final int CHOOSE_PHOTO = 2;
    private CircleImageView circleImage;
    private EditText studentId;
    private EditText studentName;
    private EditText studentClass;
    private Button rollCall;
    private String student_Id;
    private String student_Name;
    private String student_Class;
    private File outputImage;
    private Uri imageUri;
    private static final String LOGIN_URL = "http://192.168.43.158:8081/Testserver/login";
    private static final String REGISTER_URL = "http://192.168.43.158:8081/Testserver/register";
    private ProgressDialog progressDialog;
    private SharedPreferences prefs;
    private Button firstEnter;
    private String android_ID;
    private String install_ID;
    private String wifiMacAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        initView();
        setText();
        setListener();
    }

    /**
     * 设置EditText的文本
     */
    private void setText() {
        studentId.setText(prefs.getString("student_Id",""));
        studentName.setText(prefs.getString("student_Name",""));
        studentClass.setText(prefs.getString("student_Class",""));
    }
    //设置监听器
    private void setListener() {
        circleImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
        rollCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                studentEntry(LOGIN_URL);
            }
        });
        firstEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                studentEntry(REGISTER_URL);
            }
        });
    }
    //点击头像弹出对话框Dialog
    private void showDialog() {
        final String[] items=getResources().getStringArray(R.array.picture_item);
        new AlertDialog.Builder(this)
                .setTitle(getString(R.string.select))
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        String item = items[i];
                        if (item.equals("用相机拍摄照片")){
                            createFile();
                            if (Build.VERSION.SDK_INT>=24){
                                imageUri = FileProvider.getUriForFile(MainActivity.this,"cn.edu.jssvc.rollcall.fileprovider",outputImage);
                            }else {
                                imageUri = Uri.fromFile(outputImage);
                            }
                            openCamera();
                        }else {
                            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                                ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                            }else {
                                openAlbum();
                            }
                        }
                    }
                })
                .show();
    }
    //打开相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);
    }

    //打开相机拍照
    private void openCamera() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,TAKE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length > 0&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                } else {
                    Toast.makeText(MainActivity.this,"You denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    //处理拍照或选取照片的返回的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK){
                    String imagePath = Environment.getExternalStorageDirectory()+"/output_image.jpg";
                    Log.e("adadadada--------",imagePath);
                    Glide.with(this).load(imagePath).into(circleImage);
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK ){
                    if (Build.VERSION.SDK_INT>=19){
                        handleImageOnKitKat(data);
                    }else {
                        handleImageBeforeKitKit(data);
                    }
                }
            default:
                break;
        }
    }

    private void handleImageBeforeKitKit(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this,uri)){
            //如果是document类型的Uri，则通过document id 处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID+"="+id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri,null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }
    //展示相册的照片
    private void displayImage(String imagePath) {
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            circleImage.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();
        }


    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null,null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //创建一个空文件output_image.jpg
    private void createFile() {
        outputImage = new File(Environment.getExternalStorageDirectory(),"output_image.jpg");
        try {
            if (outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //发送签到请求
    private void setRequest(final String URL) {
        showRequestDialog();

        RequestBody requestBody = new FormBody.Builder()
                            .add("student_id",student_Id)
                            .add("student_name",student_Name)
                            .add("student_class",student_Class)
                            .add("android_id",android_ID)
                            .build();
        Log.e("请求------------------",student_Id+student_Name+student_Class+android_ID);
        HttpUtil.sendOkHttpRequest(URL, requestBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeRequestDialog();
                        showAlertDialog(getString(R.string.tip),"请求失败-------------------");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeRequestDialog();
                        if (URL.equals("http://192.168.43.158:8081/Testserver/login")){
                            if (responseText.equals("200")){
                                Toast.makeText(MainActivity.this,"签到成功",Toast.LENGTH_SHORT).show();
                            }
                            if (responseText.equals("500")){
                                Toast.makeText(MainActivity.this,"签到失败", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            if (responseText.equals("200")){
                                Toast.makeText(MainActivity.this,"第一次录入成功",Toast.LENGTH_SHORT).show();
                            }
                            if (responseText.equals("500")){
                                Toast.makeText(MainActivity.this,"第一次录入失败", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                });
            }
        });
    }
    //签到的进入方法
    private void studentEntry(String URL) {
        student_Id =studentId.getText().toString();
        student_Name = studentName.getText().toString();
        student_Class = studentClass.getText().toString();
        android_ID = getAndroidId();
        install_ID = getInstalltionId(getApplicationContext());
        wifiMacAddress = getWifiMacAddress();
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("student_Id",student_Id);
        editor.putString("student_Name",student_Name);
        editor.putString("student_Class",student_Class);
        editor.commit();
        if (student_Id.equals("")){
            showAlertDialog(getString(R.string.tip),getString(R.string.studentId_not_empty));
            return;
        }
        if (student_Name.equals("")){
            showAlertDialog(getString(R.string.tip),getString(R.string.studentName_not_empty));
            return;
        }
        if (student_Class.equals("")){
            showAlertDialog(getString(R.string.tip),getString(R.string.studentClass_not_empty));
            return;
        }
        setRequest(URL);
    }

    //获取Wifi Mac地址
    private String getWifiMacAddress() {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String wifiMacAddress = info.getMacAddress();
        return wifiMacAddress;
    }


    //获取Installtion Id
    private String getInstalltionId(Context context) {
        File installation = new File(context.getFilesDir(), "INSTALLATION");
        try {
            if (!installation.exists())
                writeInstallationFile(installation);
            String sID = readInstallationFile(installation);
            return sID;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static String readInstallationFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeInstallationFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }

    //获取Android Id
    private String getAndroidId() {
        return Settings.System.getString(getContentResolver(),Settings.System.ANDROID_ID);
    }


    private void showAlertDialog(String title, String message) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(getString(R.string.ok),null)
                .show();
    }

    private void showRequestDialog() {
         if (progressDialog == null){
             progressDialog = new ProgressDialog(this);
             progressDialog.setMessage(getString(R.string.waitting));
             progressDialog.setCanceledOnTouchOutside(false);
         }
        progressDialog.show();
    }
    private void closeRequestDialog(){
        if (progressDialog != null){
            progressDialog.dismiss();
        }
    }
    //初始化控件
    private void initView() {
        circleImage = (CircleImageView) findViewById(R.id.icon_image);
        studentId = (EditText) findViewById(R.id.student_id);
        studentName = (EditText) findViewById(R.id.student_name);
        studentClass = (EditText) findViewById(R.id.student_class);
        rollCall = (Button) findViewById(R.id.roll_call);
        firstEnter = (Button) findViewById(R.id.first_enter);
    }


}
